package springboot.houbank.com.MailSenderUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * Created by zhaoqiguo on 2016/9/9.
 */
@Component
public class MailSenderUtil {
    @Autowired
    private JavaMailSender mailSender;

    /**
     * 简单邮件发送
     * @param from
     * @param to
     * @param subject
     * @param text
     */
    public void sendSimpleMail(String from,String to,String subject,String text){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
    }

    /**
     * 含有附件的邮件发送
     * @param from
     * @param to
     * @param subject
     * @param text
     * @param file
     * @throws Exception
     */
    public void sendAttachmentsMail(String from,String to,String subject,String text,File file)throws Exception{

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
        mimeMessageHelper.setFrom(from);
        mimeMessageHelper.setTo(to);
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(text);

        FileSystemResource filer = new FileSystemResource(file);
        mimeMessageHelper.addAttachment("附件-1.jpg",filer);
        mailSender.send(mimeMessage);
    }

}
